//
//  RBRetrieveGetCodeVC.m
//  zhongzhenglu
//
//  Created by XL on 2022/7/5.
//

#import "RBRetrieveGetCodeVC.h"
#import "RBDefine.h"
#import "RBNavigationBar.h"
#import "UIView+RBAdd.h"
#import <UINavigationController+FDFullscreenPopGesture.h>
#import <Masonry.h>
#import "RBGradientView.h"
#import <UIColor+YYAdd.h>
#import <UIView+YYAdd.h>
#import "RBLoginRuleView.h"
#import "RBTextField.h"
#import "RanTool.h"
#import "RBTimerButton.h"
#import "RBRetrieveSetPasswordVC.h"
#import <NSDate+YYAdd.h>
#import "UINavigationController+RBAdd.h"
#include "UIViewController+RBAdd.h"
#import "RBSmsResponse.h"
#import "RBVerifyPhoneResponse.h"

@interface RBRetrieveGetCodeVC ()

@property(nonatomic, strong)RBGradientView *bgView;
@property(nonatomic, strong)RBNavigationBar *navigationBar;
@property(nonatomic, strong)IBOutlet UIView *topView;
@property(nonatomic, strong)IBOutlet UILabel *tipL;
@property(nonatomic, strong)IBOutlet RBTextField *codeF;
@property(nonatomic, strong)IBOutlet UIStackView *codeDisplayView;
@property(nonatomic, strong)IBOutlet RBTimerButton *timerBtn;

@property(nonatomic, assign)BOOL validating;

@end

@implementation RBRetrieveGetCodeVC

#pragma mark - Lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setup];
}

#pragma mark - Private

- (void)setup
{
    self.fd_prefersNavigationBarHidden = YES;
    self.view.backgroundColor = UIColor.whiteColor;
    self.bgView.hidden = NO;
    self.navigationBar.hidden = NO;
    
    __weak typeof(self) weakSelf = self;
    self.tipL.text = [NSString stringWithFormat:@"验证码已发送至%@", self.phone];
    self.codeF.type = RBTextFieldTypePhone;
    self.codeF.maxTextLength = 4;
    self.codeF.textChangeBlock = ^(NSString *text) {
        NSArray *disViews = weakSelf.codeDisplayView.arrangedSubviews;
        for (NSInteger i = 0; i < disViews.count; i++)
        {
            UIView *itemView = disViews[i];
            UILabel *disL = (UILabel *)[itemView viewWithTag:3];
            if (i >= text.length)
            {
                disL.text = nil;
            }
            else
            {
                disL.text = [text substringWithRange:NSMakeRange(i, 1)];
            }
        }
        if (text.length == weakSelf.codeF.maxTextLength)
        {
            if (!weakSelf.validating)
            {
                weakSelf.validating = YES;
                [weakSelf verify];
            }
        }
    };
    [self.codeF becomeFirstResponder];
    self.timerBtn.timerKey = [NSString stringWithFormat:@"%@-%@",NSStringFromClass(self.class), [NSDate.date stringWithFormat:@"yyyy-MM-dd HH:mm:ss"]];
    self.timerBtn.customSettingBlock = ^(RBTimerButton *btn, NSTimeInterval cdF, NSInteger cdI, BOOL countingDown) {
        if (countingDown)
        {
            [btn setAttributedTitle:[RanTool attributeStringMaker:^(NSMutableArray *maker) {
                [maker addAttributeStringWithFont:[UIFont systemFontOfSize:Zoom(15)] color:[UIColor colorWithHexString:@"#195DDB"] string:[NSString stringWithFormat:@"%zdS ", cdI]];
                [maker addAttributeStringWithFont:[UIFont systemFontOfSize:Zoom(15)] color:[UIColor colorWithHexString:@"#333333"] string:@" 后可重新发送验证码"];
            }] forState:UIControlStateNormal];
        }
        else
        {
            [btn setAttributedTitle:[RanTool attributeStringMaker:^(NSMutableArray *maker) {
                [maker addAttributeStringWithFont:[UIFont systemFontOfSize:Zoom(15)] color:[UIColor colorWithHexString:@"#195DDB"] string:@"发送验证码"];
            }] forState:UIControlStateNormal];
        }
    };
    [self.timerBtn config];
    
    [self.topView zoomSubViewsWithSelf];
    self.topView.height = Zoom(self.topView.height);
    [self.view addSubview:self.topView];
    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.mas_equalTo(self.navigationBar.mas_bottom).offset(Zoom(50));
        make.height.mas_equalTo(self.topView.height);
    }];
    
    [self.timerBtn startTimer];
}

#pragma mark - Network

- (void)verify
{
    __weak typeof(self) weak_self = self;
    [self viewLoadDataWithParam:^(NSMutableDictionary *dicM) {
        dicM[@"sms_id"] = self.sms_id;
        dicM[@"sms_code"] = self.codeF.text;
    } path:@"han_getsmsphone" post:YES log:YES responseClass:RBVerifyPhoneResponse.class desView:self.view showHud:YES showPlaceHolder:NO sucBlock:^(RBVerifyPhoneResponse *data) {
        if(data.user_id.intValue == 0)
        {
            [weak_self.view showTip:@"该手机号未注册" completion:^{
                [weak_self.navigationController popViewControllerAnimated:YES];
            }];
        }
        else
        {
            RBRetrieveSetPasswordVC *vc = RBRetrieveSetPasswordVC.new;
            vc.id = data.user_id;
            [weak_self.navigationController pushToViewController:vc animated:YES removeVcCount:2];
        }
        weak_self.validating = NO;
    } failBlock:^(RBResponse *data) {
        [weak_self.view showTip:data.message completion:nil];
        weak_self.validating = NO;
    } reloadBlock:nil];
}

#pragma mark - Event

- (IBAction)codeDisplayViewTapped:(id)sender
{
    [self.codeF becomeFirstResponder];
}

- (IBAction)timerBtnTapped:(id)sender
{
    __weak typeof(self) weak_self = self;
    [self viewLoadDataWithParam:^(NSMutableDictionary *dicM) {
        dicM[@"mobile"] = self.phone;
    } path:@"han_getsmscode" post:YES log:YES responseClass:RBSmsResponse.class desView:self.view showHud:YES showPlaceHolder:NO sucBlock:^(RBSmsResponse *data) {
        weak_self.sms_id = data.data.sms_id;
        [weak_self.timerBtn startTimer];
    } failBlock:^(RBResponse *data) {
        [weak_self.view showTip:data.message completion:nil];
    } reloadBlock:nil];
}

#pragma mark - Setter

#pragma mark - Getter

- (RBGradientView *)bgView
{
    if (!_bgView)
    {
        self.bgView = ({
            RBGradientView *view = [RBGradientView gradientViewWithColors:@[[UIColor colorWithHexString:@"#CADCFF"], [UIColor colorWithHexString:@"#ffffff"]] locations:@[@0, @1] vertical:YES];
            [self.view addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.top.right.mas_equalTo(0);
                make.height.mas_equalTo(595);
            }];
            view;
        });
    }
    return _bgView;
}

- (RBNavigationBar *)navigationBar
{
    if (!_navigationBar)
    {
        self.navigationBar = ({
            RBNavigationBar *bar = RBNavigationBar.new;
            bar.needGradientView = NO;
            [self.view addSubview:bar];
            [bar mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.top.right.mas_equalTo(0);
                make.height.mas_equalTo(kRBStatusBarHeight + kRBNavigationBarHeight);
            }];
            [bar.naviBar addBackBtnWithWidth:70 image:[UIImage imageNamed:@"backBlack"]];
            bar;
        });
    }
    return _navigationBar;
}

@end
